<?php

namespace App\Kuafu\Mybank\Logging;

use App\Library\FeiShu\SendFs;
use Monolog\DateTimeImmutable;
use Monolog\Processor\ProcessorInterface;

/**
 * Adds value of getmypid into records
 *
 * @author Andreas Hörnicke
 */
class ErrorProcessor implements ProcessorInterface
{
    /**
     * {@inheritDoc}
     */
    public function __invoke(array $record): array
    {
        if (in_array($record['level_name'], ['NOTICE', 'ERROR', 'EMERGENCY'])) {

            $title = '';
            if (!empty($record['context']['errMsg'])) {
                if (!empty($record['context']['errMsg']->message)) {
                    $title = $record['context']['errMsg']->message;
                }
            }

            $title        = vsprintf("%s(%s):%s", [$title, $record['level_name'], $record['message']]);
            $fsNotifyUids = $record['context']['fsNotifyUids'] ?? [];
            unset($record['context']['fsNotifyUids']);

            $exception = $record['context']['exception'] ?? json_encode([]);


            $fsMessage = json_encode($record['context'], 256);

            $url     = app('request')->fullUrl();
            $content = <<<CON
requestUrl: {$url}
time: {$record['datetime']->format('Y-m-d H:i:s')}

exception : {$exception}

content: {$fsMessage}

CON;

            SendFs::newRobot(SendFs::ROBOT_BATCH_BILL_MATCH)
                  ->setTitleContent($title, $content)
                  ->setAtUids($fsNotifyUids)
                  ->send();
        }

        return $record;
    }
}
